import pygetwindow as gw
import mss
import mss.tools
import cv2

import os
import time
import keyboard

border_width = 8   # 根据操作系统调整，Windows 边框一般为 8 像素
title_bar_height = 30  # 根据操作系统调整，Windows 标题栏一般为 30 像素

def capture_jump_game_window(imgname='window.png'):
    # 尝试获取跳一跳窗口
    target_window_title = "跳一跳"  # 修改
    windows = gw.getWindowsWithTitle(target_window_title)
    if not windows:
        return -1
    # 获取目标窗口
    game_window = windows[0]
    # 调整窗口内容区域
    left = game_window.left + border_width
    top = game_window.top + title_bar_height
    right = game_window.right - border_width
    bottom = game_window.bottom - border_width
    # print(f"窗口内容位置和大小: 左上角({left}, {top}) - 右下角({right}, {bottom})")
    # 使用 mss 截取屏幕
    with mss.mss() as sct:
        monitor = {"top": top, "left": left, "width": right - left, "height": bottom - top}
        screenshot = sct.grab(monitor)
        # 保存截图到文件
        mss.tools.to_png(screenshot.rgb, screenshot.size, output=imgname)
        return (top, left, bottom, right)

def is_page(image_path, template_path="sample_begin.png", threshold=0.7):
    try:
        # 读取截图和模板图像
        screenshot = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
        template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE)
        if screenshot is None or template is None:
            # print("[E] 无法加载截图或模板图像")
            return -1
        # 获取模板图像的尺寸
        # template_height, template_width = template.shape
        # 尝试不同的缩放比例来进行多尺度匹配
        scales = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 1.1, 1.2, 1.3]
        for scale in scales:
            # 调整模板图像大小
            resized_template = cv2.resize(template, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
            # resized_height, resized_width = resized_template.shape
            # 模板匹配
            result = cv2.matchTemplate(screenshot, resized_template, cv2.TM_CCOEFF_NORMED)
            _, max_val, _, max_loc = cv2.minMaxLoc(result)
            # 如果匹配值达到阈值，则返回匹配位置
            if max_val >= threshold:
                # 在匹配图像上绘制匹配结果
                # print(f"[+] 模板匹配成功，匹配值: {max_val}, 位置: {max_loc}, 缩放比例: {scale}")
                return max_loc
            # else:
            #     print(f"[-] 尝试缩放比例 {scale} 时，匹配值: {max_val}")
        # print("[E] 没有找到匹配的模板")
        return -1
    except Exception as e:
        print(f"[E] 模板匹配出错: {e}")
        return -1

if __name__ == '__main__':
    # Create the screenshots directory if it doesn't exist
    if not os.path.exists("screenshots"):
        os.makedirs("screenshots")

    # Listen for Enter key to capture window screenshots
    print("Press Enter to capture a screenshot of the game window.")
    print("Press 'q' to quit.")
    while True:
        if keyboard.is_pressed('enter'):  # Wait for Enter key press
            timestamp = time.strftime("%Y%m%d_%H%M%S")
            imgname = f"./screenshots/{timestamp}.png"  # Add timestamp for unique filenames
            capture_jump_game_window(imgname)
            time.sleep(0.5)  # Add a small delay to avoid multiple captures in a short time

        if keyboard.is_pressed('q'):  # Press 'q' to quit the program
            print("Exiting...")
            break